﻿using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace System {
    /// <summary>
    /// 缓存接口实现
    /// </summary>
    public class MemoryCacheService:ICacheService {
        protected IMemoryCache _cache;
        public MemoryCacheService() {
            var provider = new ServiceCollection().AddMemoryCache().BuildServiceProvider();
            _cache=provider.GetService<IMemoryCache>();
        }
        public MemoryCacheService(IMemoryCache cache) {
            _cache=cache;
        }
        public bool Add(string key,object value,int ExpirtionTime = 20) {
            if(!string.IsNullOrEmpty(key)) {
                Random r = new Random();
                int num = r.Next(20,1440);
                var time = DateTime.Now.AddMinutes(ExpirtionTime+num);
                if(Exists(key)) {
                    Remove(key);
                }
                _cache.Set(key,value,time);
                CacheHelper.CacheKeys.Add(key);
            }
            return true;
        }
        public bool Remove(string key) {
            if(string.IsNullOrEmpty(key)) {
                return false;
            }
            if(Exists(key)) {
                _cache.Remove(key);
                CacheHelper.CacheKeys.Remove(key);
                return true;
            }
            return false;
        }
        public void RemoveAll() {
            for(int i = 0;i<CacheHelper.CacheKeys.Count;i++) {
                string key = CacheHelper.CacheKeys[i];
                if(Exists(key)) {
                    _cache.Remove(key);
                    CacheHelper.CacheKeys.Remove(key);
                }
            }
        }
        public string GetValue(string key) {
            if(string.IsNullOrEmpty(key)) {
                return null;
            }
            if(Exists(key)) {
                return _cache.Get(key).ToString();
            }
            return null;
        }
        public object GetObject(string key) {
            if(string.IsNullOrEmpty(key)) {
                return null;
            }
            if(Exists(key)) {
                return _cache.Get(key);
            }
            return null;
        }
        public T GetObject<T>(string key) {
            var obj = GetObject(key);
            if(obj!=null) {
                return (T)obj;
            }
            return default(T);
        }
        public bool Exists(string key) {
            bool flg = false;
            if(string.IsNullOrEmpty(key)) {
                return flg;
            }
            object cache;
            flg=_cache.TryGetValue(key,out cache);
            if(!flg) CacheHelper.CacheKeys.Remove(key);
            return flg;
        }
    }
}
